package com.sx.gongzhong.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sx.gongzhong.R;
import com.sx.gongzhong.activity.ConvenniceAnnounceActivity;
import com.sx.gongzhong.activity.ConvenniceAppealActivity;
import com.sx.gongzhong.activity.DefendRoadActivity;
import com.sx.gongzhong.activity.ExposureDetailActivity;
import com.sx.gongzhong.activity.ExposureSearchActivity;
import com.sx.gongzhong.activity.GuidanceActivity;
import com.sx.gongzhong.activity.HelpActivity;
import com.sx.gongzhong.activity.LegalAdviceActivity;
import com.sx.gongzhong.activity.MoreEntranceActivity;
import com.sx.gongzhong.activity.PromotePeaceActivity;
import com.sx.gongzhong.activity.WebActivity;
import com.sx.gongzhong.adapter.ExposureListAdapter;
import com.sx.gongzhong.adapter.MainPageEntranceAdapter;
import com.sx.gongzhong.adapter.viewholder.BannerHolderView;
import com.sx.gongzhong.model.BannerBean;
import com.sx.gongzhong.model.EntranceBean;
import com.sx.gongzhong.model.ExposureBean;
import com.sx.gongzhong.model.MsgEvent;
import com.sx.gongzhong.net.MyRxBus;
import com.sx.gongzhong.pest.BannerPest;
import com.sx.gongzhong.pest.ExposureListPest;
import com.sx.gongzhong.utils.AppConstants;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.view.BannerView;
import com.sx.gongzhong.view.IExposureListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by XZY on 2017/12/28.
 */

public class MainPagerFragment extends LazyFragment implements SwipeRefreshLayout.OnRefreshListener, BannerView, IExposureListView {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;

    private ConvenientBanner banner;
    private GridView gv;
    private MainPageEntranceAdapter entranceAdapter;

    private ExposureListAdapter exposureListAdapter;

    String[] names = new String[]{"便民公告","便民诉求","互帮互助","办事指南",
            "法律咨询","全民护路", "平安宣传","更多"};
    int[] icons = new int[]{R.mipmap.icon_home_announcement,R.mipmap.icon_home_appeal, R.mipmap.icon_home_help, R.mipmap.icon_home_guide,
            R.mipmap.icon_home_law, R.mipmap.icon_home_mow, R.mipmap.icon_home_propaganda,R.mipmap.icon_home_more};

    ArrayList<ExposureBean> exposureBeanList = new ArrayList<ExposureBean>();
    private Disposable disposable;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main_pager, container, false);
        ButterKnife.bind(this, view);
        initView();
        getData();
        initRx();
        return view;
    }

    private void initRx() {
        disposable = MyRxBus.get().toObservable(MsgEvent.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent msgEvent) throws Exception {
                        if ("MainPagerFragment".equals(msgEvent.getRequest())) {
                            getExpData();
                        }
                    }
                });
    }

    private void getExpData() {
        new ExposureListPest(this).loadExposureList("","",1,8);
    }

    private void getData() {
        new BannerPest(this).getBanner(getActivity());
        getExpData();
    }

    private void initView() {
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setColorSchemeResources(AppConstants.colors);
            swipeRefreshLayout.setOnRefreshListener(this);
        }
        View headView = getActivity().getLayoutInflater().inflate(R.layout.mian_head,null);
        banner = (ConvenientBanner) headView.findViewById(R.id.banner);
        List<EntranceBean> entranceBeanList = new ArrayList<EntranceBean>();
        for(int i =0 ; i < names.length ; i ++){
            EntranceBean serviceBean = new EntranceBean();
            serviceBean.icon = icons[i];
            serviceBean.name = names[i];
            entranceBeanList.add(serviceBean);
        }
        gv = (GridView) headView.findViewById(R.id.gv);
        entranceAdapter = new MainPageEntranceAdapter(getActivity(), R.layout.adapter_item_entrance,entranceBeanList);
        gv.setAdapter(entranceAdapter);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0://便民公告
                        startActivity(new Intent(getActivity(),ConvenniceAnnounceActivity.class));
                        break;
                    case 1://便民诉求
                        startActivity(new Intent(getActivity(), ConvenniceAppealActivity.class));
                        break;
                    case 2://互帮互助
                        startActivity(new Intent(getActivity(), HelpActivity.class));
                        break;
                    case 3://办事指南
                        startActivity(new Intent(getActivity(),GuidanceActivity.class));
                        break;
                    case 4://法律咨询
                        startActivity(new Intent(getActivity(),LegalAdviceActivity.class));
                        break;
                    case 5://全民护路
                        startActivity(new Intent(getActivity(),DefendRoadActivity.class));
                        break;
                    case 6://平安宣传
                        startActivity(new Intent(getActivity(),PromotePeaceActivity.class));
                        break;
                    case 7:
                        startActivity(new Intent(getActivity(),MoreEntranceActivity.class));
                        break;
                }
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
        exposureListAdapter = new ExposureListAdapter(getActivity(),R.layout.item_exposure_list,exposureBeanList);
        exposureListAdapter.setHeaderAndEmpty(true);
        exposureListAdapter.setEmptyView(View.inflate(getActivity(),R.layout.load_error_view,null));
        exposureListAdapter.addHeaderView(headView);
        recyclerView.setAdapter(exposureListAdapter);
        exposureListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(getActivity(), ExposureDetailActivity.class)
                        .putExtra("ExposureID",exposureBeanList.get(position).getId()));
            }
        });
    }

    @OnClick({R.id.tv_search})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.tv_search:
                startActivity(new Intent(getActivity(),ExposureSearchActivity.class));
                break;
        }
    }

    @Override
    public void onDestroyView() {
        if (disposable != null){
            disposable = null;
        }
        super.onDestroyView();
    }

    @Override
    public void onRefresh() {
        swipeRefreshLayout.setRefreshing(false);
        getData();
    }

    @Override
    protected void lazyLoad() {
    }
    @Override
    public void showError(String message) {
        ToastUtils.showToast(getActivity(),message);
    }

    @Override
    public void getBannerSuccess(final List<BannerBean> data) {
        banner.stopTurning();
        banner.setPages(new CBViewHolderCreator() {
            @Override
            public Object createHolder() {
                return new BannerHolderView();
            }
        },data)
                //设置指示器是否可见
                .setPointViewVisible(true)
                //设置需要切换的时间
                .startTurning(3000)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        startActivity(new Intent(getActivity(), WebActivity.class)
                                .putExtra("title",data.get(position).title)
                                .putExtra("articleUrl",data.get(position).articleUrl));
                    }
                })
                //设置指示器圆点
                .setPageIndicator(new int[]{R.mipmap.img_shuffling_normal,R.mipmap.img_shuffling_selected})
                //设置指示器位置（左、中、右）+
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
    }

    @Override
    public void loadExposureList(List<ExposureBean> data, int total) {
        exposureBeanList.clear();
        exposureBeanList.addAll(data);
        exposureListAdapter.notifyDataSetChanged();
    }
}
